import axios from 'axios';
import * as constant from "./constant"
import * as auth from "./auth"
// 环境变量
let env = process.env.NODE_ENV;
env = 'development';

// development开发 test测试  production生产
let baseUrl = '';
if (env === 'development') {
    baseUrl = 'http://localhost:9001';
} else if (env === 'test') {
    baseUrl = '待配置';
} else if (env === 'production') {
    baseUrl = 'http://api.cn';
}



// 创建axios实例
const service = axios.create({
    // api 的 base_url
    baseURL: baseUrl,
    timeout: 50000 // 请求超时时间(因为需要调试后台,所以设置得比较大)
})

axios.defaults.withCredentials = true;

// request拦截器(请求前的处理)
service.interceptors.request.use(
    config => {
        const userObj = localStorage.getItem(constant.USER_INFO);
        const currentTime = Date.parse(new Date());
        if (userObj && userObj.expTime > currentTime) {
            auth.removeAuth()
            alert("过期啦!请重新登录!");
        }

        const token = localStorage.getItem(constant.USER_TOKEN);
        if (token) {
            // config.headers["token"] = localStorage.getItem(constant.USER_TOKEN);
            axios.defaults.headers.common["token"] = token
        } else{
            delete axios.defaults.headers.common["token"] 
        }
        // else {
        //     config.headers["token"] = "";
        //     alert("你暂未登录!",2000)
        //     window.location.href = "/login";
        // }
        console.log(config);
        return config
    },
    error => {
        // Do something with request error
        console.log("requestPre", error) // for debug
        return Promise.reject(error)
    }
)

// response 拦截器(数据返回后的处理)
service.interceptors.response.use(
    response => {
        console.log(response);
        const res = response.data
        if (res.code === "200" || res.code === "0") {
            // 成功
            return response.data
        } else {
            // alert(res.msg);
            return Promise.reject(res)
        }
    },
    error => {
        console.log('err' + error) // for debug
        return Promise.reject(error)
    }
)


export default service